﻿#region Copyright
// Partial Copyright (c) LogoUI Software Solutions LTD
// Author: Vladislav Spivak
// This source file is the part of LogoFX Framework http://logofx.codeplex.com
// See accompanying licences and credits.
#endregion

#if SILVERLIGHT


using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Interactivity;
using System.ServiceModel.DomainServices.Client.ApplicationServices;
using System.ComponentModel;

namespace LogoFX.Infra.Interactivity
{
    public abstract class BaseRoleBasedBehavior<T>
        : Behavior<T> where T : DependencyObject
    {

        [Category("Security Settings")]
        [Description("Associated control will only be visible if the current user is a member of one or more of these roles.")]
        public  Collection<string> AllowedRoles { get; set; }


        public BaseRoleBasedBehavior()
        {
            this.AllowedRoles = new Collection<string>();

            if (DesignTimeHelper.IsRuntime)
            {

                WebContextBase.Current.Authentication.LoggedIn += 
                    new System.EventHandler<AuthenticationEventArgs>(UpdateAssociatedObject);

                WebContextBase.Current.Authentication.LoggedOut += 
                    new System.EventHandler<AuthenticationEventArgs>(UpdateAssociatedObject);

            }
        }


        protected abstract void UpdateAssociatedObject(object sender, AuthenticationEventArgs e);

        protected override void OnAttached()
        {
            base.OnAttached();

            this.UpdateAssociatedObject(this, null);
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
        }

        protected bool IsInRole(string roleName)
        {

            if (DesignTimeHelper.IsRuntime)
            {
                return WebContextBase.Current.Authentication.User.IsInRole(roleName);
            }
            else
            {
                return true;

            }
        }

        
    }
}

#endif